<?php

namespace common\components\image_beds;

use common\components\fs\Fs;
use common\components\wtools\tools\FileHelper;
use common\components\wtools\tools\Model;
use common\models\db\Files;
use common\Tools;
use finfo;
use yii\base\Component;
use yii\di\Instance;

class EasyImageFs extends Fs
{
    /**
     * @var EasyImage $easyImage
     */
    public $easyImage = 'easyImage';

    public function init()
    {
        $this->easyImage = Instance::ensure($this->easyImage, EasyImage::className());
        parent::init();
    }

    public function uploadByTmpFile($tmp)
    {
        $tmpFile = $tmp['tmp_name'];
        $url = $this->uploadByFileRoot($tmpFile);
        return $url;
    }

    public function uploadByFileRoot($fileRoot)
    {
        $url = $this->easyImage->upload($fileRoot);
        return $url;
    }

    public function uploadByBase64($base64)
    {
        $content = base64_decode($base64);
        // 创建finfo实例，用于获取文件MIME类型
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        // 获取MIME类型
        $mime_type = $finfo->buffer($content);
        $ext = \Yii::$app->wMimeTypes->getExtension($mime_type);
        $imgBase64 = "data:$mime_type;base64,$base64";
        $md5 = md5($imgBase64);
        $size = Tools::getBase64ImgInfo($imgBase64, 'size');
        $id_file_name = $md5.".".$size.".".$ext;
        $prefix = '/files/'.date('Ymd/');
        $yiiAliasUploadsRoot = '@uploads_root';
        $filePath = \Yii::getAlias($yiiAliasUploadsRoot).$prefix.$id_file_name;
        if (!is_dir(dirname($filePath))) {
            FileHelper::createDirectory(dirname($filePath));
        }
        file_put_contents($filePath, $content);
        $url = $this->easyImage->upload($filePath);
        unlink($filePath);
        return $url;
    }
}